import 'package:eshi/app/shi/widget/WebTextWidget.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:html' as html;

/// Web环境下的iframe弹窗组件
class WebIFramePopup extends StatefulWidget {
  final String url; // 要加载的URL
  final String title; // 弹窗标题
  final int width; // 弹窗宽度
  final int height; // 弹窗高度
  final bool show; // 是否显示弹窗
  final VoidCallback onClose; // 关闭回调

  const WebIFramePopup({
    super.key,
    required this.url,
    this.title = "IFrame 弹窗",
    this.width = 800,
    this.height = 600,
    required this.show,
    required this.onClose,
  }) : assert(kIsWeb, "WebIFramePopup 仅支持Web环境");

  @override
  State<WebIFramePopup> createState() => _WebIFramePopupState();
}


class _WebIFramePopupState extends State<WebIFramePopup> {
  String? _popupId; // 弹窗唯一标识

  @override
  void initState() {
    super.initState();
    // 初始显示时创建弹窗
    if (widget.show) {
      _createIFrame();
    }
  }

  @override
  void didUpdateWidget(covariant WebIFramePopup oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 当show状态变化时更新弹窗显示
    if (widget.show && !oldWidget.show) {
      _createIFrame();
    } else if (!widget.show && oldWidget.show) {
      _destroyIFrame();
    }
    // URL变化时更新iframe src
    if (widget.url != oldWidget.url && widget.show) {
      _updateIFrameUrl();
    }
  }

  @override
  void dispose() {
    // 组件销毁时移除弹窗
    _destroyIFrame();
    super.dispose();
  }

  /// 创建iframe弹窗
  void _createIFrame() {
    if (!kIsWeb || _popupId != null) return;

    // 生成唯一ID
    _popupId = "iframe-popup-${DateTime.now().millisecondsSinceEpoch}";

    // 创建遮罩层
    final overlay = html.DivElement()
      ..id = "${_popupId}-overlay"
      ..style.position = "fixed"
      ..style.top = "0"
      ..style.left = "0"
      ..style.width = "100%"
      ..style.height = "100%"
      ..style.backgroundColor = "rgba(0, 0, 0, 0.5)"
      ..style.zIndex = "9998"
      ..style.display = "flex"
      ..style.alignItems = "center"
      ..style.justifyContent = "center"
      ..style.transition = "opacity 0.3s";

    // 创建弹窗容器
    final popupContainer = html.DivElement()
      ..id = _popupId!
      ..style.width = "${widget.width}px"
      ..style.height = "${widget.height}px"
      ..style.backgroundColor = "white"
      ..style.borderRadius = "8px"
      ..style.boxShadow = "0 4px 12px rgba(0, 0, 0, 0.15)"
      ..style.overflow = "hidden"
      ..style.position = "relative"
      ..style.transform = "scale(0.9)"
      ..style.transition = "transform 0.3s";

    // 标题栏
    final titleBar = html.DivElement()
      ..style.padding = "12px 16px"
      ..style.backgroundColor = "#f5f5f5"
      ..style.borderBottom = "1px solid #eee"
      ..style.display = "flex"
      ..style.justifyContent = "space-between"
      ..style.alignItems = "center";

    // 标题文本
    titleBar.append(html.HeadingElement.h4()
      ..text = widget.title
      ..style.margin = "0"
      ..style.fontSize = "16px");

    // 关闭按钮
    final closeButton = html.ButtonElement()
      ..text = "×"
      ..style.border = "none"
      ..style.backgroundColor = "transparent"
      ..style.fontSize = "20px"
      ..style.cursor = "pointer"
      ..style.color = "#666"
      ..onClick.listen((_) {
        Navigator.pop(context);
         widget.onClose();
      });

    titleBar.append(closeButton);

    // 创建iframe
    final iframe = html.IFrameElement()
      ..id = "${_popupId}-iframe"
      ..src = widget.url
      ..style.width = "100%"
      ..style.height = "${widget.height - 45}px" // 减去标题栏高度
      ..style.border = "none";

    // 组装弹窗
    popupContainer.append(titleBar);
    popupContainer.append(iframe);
    overlay.append(popupContainer);

    // 添加到页面
    html.document.body?.append(overlay);

    // 动画效果
    Future.delayed(const Duration(milliseconds: 10), () {
      popupContainer.style.transform = "scale(1)";
    });

    // 点击遮罩层关闭
    overlay.onClick.listen((event) {
      if (event.target == overlay) {
          Navigator.pop(context);
          widget.onClose();
      }
    });
  }

  /// 更新iframe的URL
  void _updateIFrameUrl() {
    if (!kIsWeb || _popupId == null) return;
    final iframe = html.document.getElementById("${_popupId}-iframe") as html.IFrameElement?;
    iframe?.src = widget.url;
  }

  /// 销毁iframe弹窗
  void _destroyIFrame() {
    if (!kIsWeb || _popupId == null) return;

    // 移除弹窗和遮罩层
    html.document.getElementById(_popupId!)?.remove();
    html.document.getElementById("${_popupId}-overlay")?.remove();
    _popupId = null;
  }

  @override
  Widget build(BuildContext context) {
    // Web环境下Widget不渲染任何内容（通过DOM操作实现弹窗）
    // 非Web环境显示提示
    return kIsWeb ? const SizedBox.shrink() : const Text("仅Web环境支持iframe弹窗");
  }
}

